package com.falcon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.falcon.core.utils.BeanUtils;
import com.falcon.mapper.IColumnMapper;
import com.falcon.mapper.ITableMapper;
import com.falcon.mvc.domain.BasePager;
import com.falcon.service.ITableService;
import com.falcon.domain.dos.TableDO;
import com.falcon.domain.po.ColumnPO;
import com.falcon.domain.po.TablePO;
import com.falcon.domain.req.TableQuery;
import com.falcon.domain.req.TableRequest;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.swan.mybatis.condition.Condition;
import com.swan.mybatis.condition.OpType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class TableService implements ITableService {

    @Autowired
    private ITableMapper tableMapper;

    @Autowired
    private IColumnMapper columnMapper;

    @Override
    public Long save(TableRequest request){
        TablePO tablePO = BeanUtil.copyProperties(request, TablePO.class);

        this.tableMapper.insertNotNull(tablePO);

        return tablePO.getId();
    }

    @Override
    public Boolean update(Long id, TableRequest request){

        TablePO tablePO = BeanUtil.copyProperties(request, TablePO.class);
        tablePO.setId(id);

        return this.tableMapper.updateNotNull(tablePO);
    }

    @Override
    public Boolean deleteById(Long id) {

        Condition condition = Condition.newInstance()
                .and(ColumnPO.Fields.tableId, OpType.equals, id);
        List<ColumnPO> columns = this.columnMapper.selectList(condition);

        List<Long> ids = columns.stream().map(ColumnPO::getId).collect(Collectors.toList());

        if (!ids.isEmpty()) {
            this.columnMapper.deleteByIds(ids);
        }

        return this.tableMapper.deleteById(id);
    }

    @Override
    public TableDO queryById(Long id){

        TablePO tablePO = this.tableMapper.selectById(id);

        TableDO tableDO = BeanUtil.copyProperties(tablePO, TableDO.class);

        return tableDO;
    }


    @Override
    public List<TableDO> queryList(TableQuery request){

        Condition condition = request.toCondition();

        List<TablePO> poList = this.tableMapper.selectList(condition);

        List<TableDO> doList = BeanUtil.copyToList(poList, TableDO.class);

        return doList;
    }

    @Override
    public BasePager<TableDO> queryPager(TableQuery request){


        PageInfo<TablePO> pageInfo = PageHelper.startPage(request.getPage(), request.getPageSize())
                .doSelectPageInfo(() -> this.tableMapper.selectList(request.toCondition()));

        return BeanUtils.toPager(pageInfo, TableDO.class);
    }

    @Override
    public int batchDelete(List<Long> ids) {

        return this.tableMapper.deleteByIds(ids);
    }


}
